package de.hdm.articastle;

import java.util.Date;

import de.hdm.articastle.physics.Ballistic;
import de.hdm.articastle.physics.LandscapeGenerator;

public class World {
	public static final int WORLD_WIDTH = 480;
	public static final int WORLD_HEIGHT = 320;
	public static final int castleSize = 42;
	public static final int bulletSize = 16;
	
	public Bullet bullet;
	public Castle castle1;
	public Castle castle2;
	public AimPoint aimpoint;
	int[] landscape;
	public int currentPlayer = 1;
	
	public World() {
		landscape = LandscapeGenerator.generateLandscape(
				WORLD_WIDTH, WORLD_HEIGHT, true);
		
		int x = 10;
		for (int i = x + 1; i < x + castleSize; i++) {
			landscape[i] = landscape[x];
		}
		castle1 = new Castle(x, landscape[x], castleSize);
		
		x = WORLD_WIDTH - 10;
		for (int i = x - 1; i > x - castleSize; i--)
		{
			landscape[i] = landscape[x];
		}
		castle2 = new Castle(x - castleSize, landscape[x], castleSize);
	}
	
	public void update(float deltaTime) {
		if (bullet != null)
		{
			double time = ((new Date().getTime() - bullet.time) / 1000.0);
			if (time < bullet.endTime)
				bullet = Ballistic.calculateParabola(bullet, 0.0, time);
			else
			{
				if (bullet.hit1)
				{
					castle1.damage++;
				}
					
				if (bullet.hit2)
				{
					castle2.damage++;
				}
					
				bullet = null;
			}
		}
	}
	
	public void calculateEndPoints()
	{
		boolean isOut = false;
		boolean isHitGround = false;
		boolean isHit = false;
		double time = 0.0;
		Bullet tempBullet = new Bullet(bullet);
		
		while (!isOut && !isHit && !isHitGround)
		{
			time += 0.1;
			tempBullet = Ballistic.calculateParabola(tempBullet, 0.0, time);
			if (tempBullet.x < 0 || tempBullet.x > World.WORLD_WIDTH)
				isOut = true;
			else if (tempBullet.y < landscape[tempBullet.x])
				isHitGround = true;
			else if (tempBullet.x >= castle1.x && 
					tempBullet.x <= castle1.x + castle1.size &&
					tempBullet.y >= castle1.y &&
					tempBullet.y <= castle1.y + castle1.size)
			{
				bullet.hit1 = true;
				isHit = true;
			}
			else if (tempBullet.x >= castle2.x && 
					tempBullet.x <= castle2.x + castle2.size &&
					tempBullet.y >= castle2.y &&
					tempBullet.y <= castle2.y + castle2.size)
			{
				bullet.hit2 = true;
				isHit = true;	
			}						
		}
		
		bullet.endTime = time;
		bullet.endX = tempBullet.x;
		bullet.endY = tempBullet.y;
		bullet.setTime();
	}
}
